<?php

namespace PhpYes\Modules\Log;


final class LoggerManager
{
    /** @var null|LoggerManager */
    private static $singleObj = null;
    /** @var array */
    private $config;
    /** @var string|null */
    private $defaultName;
    /** @var array */
    private $name2LoggerArr;

    /**
     * @param array $config
     */
    public static function init($config)
    {
        self::$singleObj = new LoggerManager($config);
    }

    /**
     * @return null|LoggerManager
     */
    public static function getSingleObj()
    {
        return self::$singleObj;
    }

    /**
     * LoggerManager constructor.
     * @param array $config
     */
    private function __construct($config)
    {
        $this->config = $config;
        $this->name2LoggerArr = array();
    }

    /**
     * @return array
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param null|string $name
     * @return null|Logger
     */
    public function getLogger($name = null)
    {
        if (empty($name)) {
            $name = $this->getDefaultName();
            if (empty($name)) {
                return null;
            }
        }

        if (empty($this->name2LoggerArr[$name])) {
            $loggerConfig = empty($this->config[$name]) ? null : $this->config[$name];
            if (empty($loggerConfig)) {
                return null;
            }
            $logger = new Logger($loggerConfig);
            $this->name2LoggerArr[$name] = $logger;
        }

        return $this->name2LoggerArr[$name];
    }

    /**
     * @return null|string
     */
    public function getDefaultName()
    {
        if ($this->defaultName) {
            return $this->defaultName;
        }

        $config = $this->config;
        if (empty($config)) {
            return null;
        }

        foreach ($config as $n => $c) {
            if (is_array($c) && !empty($c['default'])) {
                $this->defaultName = $n;

                return $this->defaultName;
            }
        }

        if (!empty($config['default'])) {
            if (is_string($config['default'])) {
                $this->defaultName = $config['default'];

                return $this->defaultName;
            } else {
                $this->defaultName = 'default';

                return $this->defaultName;
            }
        }

        $this->defaultName = array_keys($config)[0];

        return $this->defaultName;
    }

}